package net.monare.mifss.evn;

import net.monare.mifss.MifssMessages;
import net.monare.mifss.admin.ui.wiz.BaseWizard;
import net.monare.mifss.admin.ui.wiz.cards.CardValidation;

import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.Notification;

public class StorageCardListener implements ClickListener {

	private static final long serialVersionUID = -3252159956995278551L;

	private BaseWizard baseWizard;
	private Component[] cards;

	public StorageCardListener(BaseWizard baseWizard, Component[] cards) {
		this.baseWizard = baseWizard;
		this.cards = cards;
	}
	
	public void buttonClick(ClickEvent event) {
			
		String buttonId = event.getButton().getId();
		
		int currIndex = getCurrentCardIndex(baseWizard, cards);
		int newIndex;
		
		if(buttonId.equals("NEXT")){
			newIndex = currIndex + 1;
		} else {
			newIndex = currIndex - 1;
		}
		
		// limit index
		if(newIndex < 0){
			newIndex = 0;
		}
		
		if(newIndex > (cards.length -1)){
			newIndex = (cards.length -1);
		}
		
		
		// is current card valid ?
		CardValidation cv = (CardValidation)cards[currIndex];
		
		if(cv.isCardValid()){
			baseWizard.setCard(cards[newIndex]);
		} else {
			Notification.show(MifssMessages.getMessage("sys.error.form.not.valid"));
		}
		
	}
	
	private int getCurrentCardIndex(BaseWizard baseWizard, Component[] cards){
		
		int index = -1;
		
		String cardId = baseWizard.getCardId();
		
		for(int i=0; i<cards.length; i++){
			if(cards[i].getId().equals(cardId)){
				index = i; 
			}
		}
		
		return index;
		
	}

}
